/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.player;

import java.io.*;
import org.codeminer.parts.library.Song;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public class MPLayer implements SongPlayer {

    private static final Logger log = LoggerFactory.getLogger(MPLayer.class);
    private final BufferedWriter processOutputStream;
    private final BufferedReader processInputStream;
    private double currentPosition = 0;
    private final Process mplayer;
    private double duration = -1;
    private boolean shuttingDown = false;
    private Song currentSong;

    public MPLayer() throws IOException {
        ProcessBuilder builder = new ProcessBuilder("mplayer", "-slave", "-idle", "-vc", "null", "-vo", "null");
        mplayer = builder.start();
        processInputStream = new BufferedReader(new InputStreamReader(mplayer.getInputStream()));
        processOutputStream = new BufferedWriter(new OutputStreamWriter(mplayer.getOutputStream()));
        start();
    }

    @Override
    public void start(Song song) {
        this.duration = -1;
        this.currentPosition = 0;
        this.currentSong = song;
        sendCommand("loadfile \"" + song.getFile().getAbsolutePath() + "\"");
    }

    @Override
    public void stop() {
        this.currentPosition = 0;
        this.currentSong = null;
        sendCommand("stop");
    }

    @Override
    public void shutdown() {
        sendCommand("q");
        this.currentPosition = 0;
        this.shuttingDown = true;
        this.currentSong = null;
        try {
            processInputStream.close();
        } catch (IOException ex) {
            log.error("could not close stream", ex);
        }
        try {
            processOutputStream.close();
        } catch (IOException ex) {
            log.error("could not close stream", ex);
        }
    }

    @Override
    public void pause() {
        sendCommand("p");
    }

    @Override
    public void resume() {
        sendCommand("p");
    }

    @Override
    public double getCurrentPosition() {
        return currentPosition;
    }

    @Override
    public Song getCurrentSong() {
        return this.currentSong;
    }

    private void sendCommand(String command) {
        if (shuttingDown) {
            throw new IllegalStateException("This player is already down. Please create a new one");
        }
        try {
            processOutputStream.write(command);
            processOutputStream.newLine();
            processOutputStream.flush();
        } catch (IOException ex) {
            log.error("could not process command", ex);
        }
    }

    private void start() {
        Thread thread = new Thread(new MplayerOutputReader());
        thread.start();
    }

    private final class MplayerOutputReader implements Runnable {

        @Override
        public void run() {
            try {
                String line = processInputStream.readLine();
                while (line != null) {
                    if (line.startsWith("A:")) {

                        String tmp = line.substring(4, line.indexOf("(") - 1);
                        double current = Double.parseDouble(tmp);

                        if (duration < 0) {
                            String durationTmp = line.substring(line.indexOf(" of "));
                            durationTmp = durationTmp.substring(4);
                            durationTmp = durationTmp.substring(0, durationTmp.indexOf("(") - 1);
                            duration = Double.parseDouble(durationTmp);
                        }

                        if (duration != 0) {
                            currentPosition = 100 * current / duration;
                        }
                    }
                    line = processInputStream.readLine();
                }
            } catch (IOException ex) {
                if (!shuttingDown) {
                    log.error("could not read mplayer output", ex);
                }
            }
        }
    }
}
